package mrpanyu.guitool.yunduan;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import mrpanyu.guitool.base.annotation.Action;
import mrpanyu.guitool.base.annotation.Parameter;
import mrpanyu.guitool.base.annotation.ToolModel;
import mrpanyu.guitool.base.model.ParameterType;
import mrpanyu.guitool.base.model.Tool;
import mrpanyu.guitool.base.util.CommonUtils;

@ToolModel(displayName = "QR二维码生成", enableProfiles = false)
public class QRGenerator {

	@Parameter(displayName = "文本内容", type = ParameterType.MULTILINE_TEXT, order = 1)
	private String content = "";

	@Parameter(displayName = "图片尺寸", type = ParameterType.TEXT, order = 2)
	private int size = 600;

	@Action(displayName = "生成", order = 1)
	public void generate(Tool tool) throws Exception {
		tool.clearMessages();
		QRCodeWriter writer = new QRCodeWriter();
		Map<EncodeHintType, Object> hints = new LinkedHashMap<>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		hints.put(EncodeHintType.MARGIN, 2);
		BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, size, size, hints);
		BufferedImage img = MatrixToImageWriter.toBufferedImage(bitMatrix);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(img, "PNG", baos);
		byte[] data = baos.toByteArray();
		File file = File.createTempFile("qr_code_", ".png");
		file.deleteOnExit();
		CommonUtils.writeBytes(file, data);
		String html = "<div><img src='file:///" + file.getAbsolutePath() + "'></div>";
		tool.htmlMessage(html);
	}

}
